<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="css/index.css">
    <link rel="stylesheet" href="router.css">
    <title>Vue Background Management System</title>    
    <style>
       
    </style>
</head>
<body>
<div id="app">
    <div class="homeBox">
        <el-container style="height: 100%" direction="vertical">
            <!-- 头部 -->
            <el-header>
              <div class="header-container" >
                <img class="img" src="assets/logo1.png" alt="" />
                <span>Background Management System</span>
              </div>

              <div>                
                <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
                <el-dropdown>                 
                    <el-button type="info" @click="exitBtn" round icon="el-icon-switch-button">                        
                        {{userInfo.name}}<i class="el-icon-arrow-down el-icon--right"></i>
                     </el-button>

                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item icon="el-icon-circle-plus">{{userInfo.phone}}</el-dropdown-item>
                      <el-dropdown-item icon="el-icon-circle-plus-outline">{{userInfo.description}}</el-dropdown-item>
                      <el-dropdown-item icon="el-icon-check">{{userInfo.menu_id}}</el-dropdown-item>
                    </el-dropdown-menu>
                 </el-dropdown>
              </div>
            

            </el-header>
            <el-container>
            <!-- 侧边 -->
            <el-aside :width="isCollapse ? '66px' : '220px'">
                <div class="toggle-button" @click="toggleCollapse">|||</div>
                <el-menu
                    background-color="#224252"
                    text-color="#fff"
                    active-text-color="#ffd04b"
                    unique-opened
                    :collapse="isCollapse"
                    :collapse-transition="false"
                    router
                    :default-active="activePath" >   
                    <!-- <Customizemenutree :sourceData="navData" /> -->
                    <div v-for="(item, index) in navData" :key="index" >

                        <el-menu-item :index="item.path" v-if="item.children.length==0"
                            :key="item.id" @click="saveRoutePath(item.path)">
                           <i :class="item.icon"></i>
                           <span slot="title"> {{ item.meta }}</span>
                        </el-menu-item>

                        <el-submenu :key="item.id" :index="item.path" v-else >
                            <template slot="title">
                                <i :class="item.icon"></i>
                                <span slot="title"> {{ item.meta }}</span>
                            </template>    
                            <!-- <el-menu-item :index="cItem.path" v-for="(cItem, cIndex) in item.children" 
                               :key="cItem.id" @click="saveRoutePath(cItem.path)">
                                <i :class="cItem.icon"></i>
                                <span slot="title">{{ cItem.meta }}</span>
                            </el-menu-item> -->
                            <div v-for="(item, index) in item.children" :key="index" >
                                <el-menu-item :index="item.path" v-if="item.children.length==0"
                                    :key="item.id" @click="saveRoutePath(item.path)">
                                   <i :class="item.icon"></i>
                                   <span slot="title"> {{ item.meta }}</span>
                                </el-menu-item>
                                <!---->
                                <el-submenu :key="item.id" :index="item.path" v-else >
                                    <template slot="title">
                                        <i :class="item.icon"></i>
                                        <span slot="title"> {{ item.meta }}</span>
                                    </template>          
                                    <el-menu-item :index="cItem.path" v-for="(cItem, cIndex) in item.children" 
                                        :key="cItem.id" @click="saveRoutePath(cItem.path)">
                                        <i :class="cItem.icon"></i>
                                        <span slot="title"> {{ cItem.meta }}</span>
                                    </el-menu-item>        
                                </el-submenu>  
                            </div>
                            
                        </el-submenu>                
                    </div>    
                </el-menu>
            </el-aside>
          <!-- 主体 -->
          <el-container>
            <el-main>
        
                <div style="padding-bottom: 20px">
                    <el-button type="text" v-if="isCollapse" @click="toggleCollapse" icon="el-icon-s-fold" style="font-size: 24px;" ></el-button>
                    <el-button type="text" v-if="isCollapse" @click="toggleCollapse" icon="el-icon-s-unfold" style="font-size: 24px;"></el-button>
    
                    <el-breadcrumb separator="/">
                        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                        <el-breadcrumb-item v-for="item in routerList" :to="{path:item.path}"
                         :key="item.path" >{{item.meta.title}}</el-breadcrumb-item>
                    </el-breadcrumb>
                </div>
    
                <router-view></router-view>
            </el-main>
            <!--<el-footer>Footer</el-footer>-->
          </el-container>
        </el-container>    
      </el-container>
    </div>
</div>
</body>
<script src="js/axios.js"></script>
<script src="js/vuex.global.js"></script>
<script src="js/store.js"></script>
<script src="js/comm.js"></script>
<script src="js/vue.js"></script>
<script src="js/vue-router.js"></script>
<script src="js/element.js"></script>
<script src="js/util.js"></script>
<script src="js/element-china-area-data.iife.js"></script>

<script src="js/xlsx.full.min.js"></script>
<script src="js/excel.js"></script>

<script src="components/find.js"></script>
<script src="utils/navData.js"></script>



<script>

const router = new VueRouter({
    mode: 'hash', //hash history      
})
router.addRoutes([
    {path:'/', name:"index",meta:{title:"建水概况"},component:{template:`<h2>主面</h2>`}},
    {path:'/login', name:"login",meta:{title:"登录"},component:()=>import('./views/login.js')},
])

var hasDynamicRouter=false
router.beforeEach(async (to, from, next) => {    

    const token = window.sessionStorage.getItem('token')
    // if (to.path=="/login" && token){
    //     next('/')
    //     return 
    // } 
    // if (to.path!=="/login" && !token){
    //    // next('/login') 
    //     window.location.href = "login.html"
    //     return 
    // } 
    if (!token) {
        window.location.href = "login.html"
    }    
  

    if(token && store.getters.getMenuTree.length==0){
         //let res=await getNavAndRouterData()

        // const data=store.getters.getMenuTree
        // console.log("routes_----",data)  
        // let routes_=menuToRouter(data)
        // router.addRoutes(routes_) //重点！！！
        // console.log("routes_----",routes_)  
    }


    next()  //--------要！！

    // if(!hasDynamicRouter){
    //     console.log("dddd",routerData)
    //     await menuToRouter(routerData)
    //     hasDynamicRouter=true
    //     return to
    // }
        //console.log("from:",from)
       // console.log("to:",to)

    //    console.log("routes_----",routes_)  
    // if(!hasDynamicRouter){
    //     const data=store.getters.getMenuTree
    //     console.log("1111",data)
    //     if(data.length>0){
    //         console.log(">0)")

    //        var routes_=[]
    //        routes_= menuToRouter(data)
    //        console.log("----menuToRouter(data)",routes_)
    //        router.addRoutes(routes_) //重点！！！ 

    //        hasDynamicRouter=true
    //     }
    //     //menuToRouter
    //    // hasDynamicRouter=true
    // }    
    // console.log("routes_22----",router.getRoutes())      
})

function getNavAndRouterData(){
    axios.post('controller/indexList.php', {
        juser_id:1
    }).then((res) => {
        console.log("---res getNavAndRouterData",res)
    
        store.commit("setmenuTree",res.data.data)

        let routes_=menuToRouter(res.data.data)
        router.addRoutes(routes_) //重点！！！
        console.log("routes_----",routes_)  
    })
}

function menuToRouter(menuTree){
    //console.log("-menuTree:",menuTree)
    let tempArray=[]
    menuTree.forEach(item => {
        tempArray.push({
            name:item.name,
            path:item.path,
            meta:{title:item.meta},
            component:item.component!=null ? ()=>import('./views/'+item.component):null,
            children: item.children.length>0 ? menuToRouter(item.children) : [],
        })                  
    });
    return tempArray    
}


Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
      menuTree:[],
      hasDynamicRouter:false,
    },
    getters:{
       getMenuTree(state){
         return state.menuTree
       },
       getHasDynamicRouter(status){
         return state.hasDynamicRouter
      } 
    },
    mutations: {             
      setmenuTree(state,menuTree){
         state.menuTree=menuTree
      },
      setHasDynamicRouter(state,status){
         state.hasDynamicRouter=status
      }
    }
})

new Vue({
    router,
    el: '#app',
    store: store,
    data() {
        return {
            activePath: '',
            isCollapse: false,
            tableH:0,

            routerList:'',  //breadcrumb 面包屑
            navData:'NavAndRouterData',
            userInfo:{},
            isShow:true,
        }
    },
    methods: {
        toggleCollapse() {
            this.isCollapse = !this.isCollapse
          
        },
        getNavRouterData(){
            axios.post('controller/indexList.php', {
                juser_id:this.userInfo.juser_id
            }).then((res) => {
                console.log("---res",res)
            
                this.loading=false                    
                this.navData=res.data.data
                //return
                store.commit("setmenuTree",res.data.data)
                
                var routes_=[]   
                 res.data.data.forEach(item => {
                    routes_.push({
                        name:item.name,
                        path:item.path,
                        meta:{title:item.meta},
                        //component:()=>import('./views/'+item.component),
                        component: () => import(`./views/${item.component}`),
                        children:  item.children?item.children.forEach(item => {             //二级 用户设置
                            routes_.push({
                                name:item.name,
                                path:item.path,
                                meta:{title:item.meta},
                                component:()=>import('./views/'+item.component),    
                                children:  item.children?item.children.forEach(item => {    //三级 log
                                    routes_.push({
                                        name:item.name,
                                        path:item.path,
                                        meta:{title:item.meta},
                                        component:()=>import('./views/'+item.component),                            
                                    },)  
                                }):[]                        
                            },)  
                        }):[]
                    },)                  
                });  //0不会出白屏

                // res.data.data.forEach(item => {
                //     routes_.push({
                //         name:item.name,
                //         path:item.path,
                //         meta:{title:item.meta},
                //         //component:()=>import('./views/'+item.component),
                //         component: () => import(`./views/${item.component}`),
                //         children:  item.children?item.children.forEach(item => {
                //             routes_.push({
                //                 name:item.name,
                //                 path:item.path,
                //                 meta:{title:item.meta},
                //                 component:()=>import('./views/'+item.component), 
                //                 children:  item.children?item.children.forEach(item => {
                //                     routes_.push({
                //                         name:item.name,
                //                         path:item.path,
                //                         meta:{title:item.meta},
                //                         component:()=>import('./views/'+item.component),                            
                //                     },)  
                //                 }):[]                           
                //             },)  
                //         }):[]
                //     },)                  
                // }); //1白屏

                // res.data.data.forEach(item => {
                //     routes_.push({
                //         name:item.name,
                //         path:item.path,
                //         meta:{title:item.meta},
                //         component:item.component!=null ? ()=>import('./views/'+item.component):null,
                //         children: item.children.length>0 ? menuToRouter(item.children) : [],
                //     })                  
                // }); //2白屏

               //routes_=menuToRouter(res.data.data) //3白屏

               router.addRoutes(routes_) //重点！！！ 
               console.log("routes_----",routes_)  
                //console.log("routes_----",router.getRoutes())        
            });           
        },
        saveRoutePath(activePath) {
            window.sessionStorage.setItem('acitvePath', activePath)
            this.activePath=activePath
        },
        exitBtn(){
            window.sessionStorage.removeItem('token')
            window.sessionStorage.removeItem('userInfo')

            this.$message.success('登录退出！')
            setTimeout(() => {
                window.location.href = "login.html"
            },1000)

        },
    },
    watch:{
        $route(to,from){
            this.routerList=to.matched;
        }
    },
    mounted(){ 
        
        this.routerList=this.$route.matched
    },
    created: function () {
        this.userInfo=JSON.parse(sessionStorage.getItem('userInfo'))
        //console.log("-userInfo--",this.userInfo)

        // this.navData=store.getters.getMenuTree
        // console.log("navData",this.navData)

       this.getNavRouterData()

        this.activePath = window.sessionStorage.getItem('acitvePath')
        this.tableH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    },
    components:{
       // Customizemenutree : pg,  //第一种方式
       // Customizemenutree : () => import('components/menutree.js')  //第二种方式
    },
})
</script>
</html>